import { _decorator, Component, Node, Vec2, Vec3, Prefab, find, Camera, Graphics, UITransform, Color, SpriteFrame, sys } from 'cc';
import { Unit, UnitEvent } from '../Entity/Unit';
import { Global, TechnologyType } from '../Util/Global';
import AssetsMgr from './AssetsMgr';
import PoolManager from '../Ctrl/PoolManager';
import GameEventMgr, { GameEvent } from './GameEventMgr';
import { Tools } from '../Util/Tools';
import { Tracker } from '../Entity/UI/Tracker';
const { ccclass, property } = _decorator;


export class GameSticker extends Component {
    type: GameStickerType;
    target: Unit;
    setTarget(target: Unit) { };
}

/**游戏内容标签 */
export enum GameStickerType {
    /**雷达标签 */
    Tracker,
    /**洛希极限提示标签 */
    RocheLimitTipSticker,
    /**星球详情 */
    PlanetEconomicSticker,
    /**锁定目标提示 */
    AimTipSticker,
}

@ccclass('GameStickerMgr')
export class GameStickerMgr extends Component {
    @property
    space: number = 10; //与边界的间隔
    graphics: Graphics = null;
    tran: UITransform = null;

    trackerPool: Tracker[] = [];
    //一个对象可能有多个标识
    allStickerMap: Map<GameStickerType, Map<Unit, GameSticker[]>> = new Map();
    screenCenter: Vec3 = new Vec3();

    private _radarCoolTime: number = 3;//雷达扫描冷却
    private _radarTick: number = 0.02;//雷达扫描间隔
    private _radarTickAngle: number = 6;//雷达每次扫描的角度范围
    private _time: number = 0;
    private _startRadar: boolean = false;
    private _enableRadar: boolean = false;

    start() {
        // let cameraCanvasNode = Global.gameManager.node;
        // cameraCanvasNode.getWorldPosition(this.screenCenter);

        this.graphics = this.getComponent(Graphics);
        this.tran = this.getComponent(UITransform);

        GameEventMgr.Register(this, GameEvent.ActivateTechnology, this.onActivateTechnologyEventHandle.bind(this));

        this._enableRadar = Global.gameManager.playerData.technologyProduct.has(TechnologyType.PlanetWarning);
    }

    onActivateTechnologyEventHandle(type: TechnologyType) {
        if (type == TechnologyType.PlanetWarning) {
            this._enableRadar = true;
        }
    }

    update(deltaTime: number) {

        Global.gameManager.node.getWorldPosition(this.screenCenter);

        for (let i = 0; i < this.trackerPool.length; i++) {
            let tracker = this.trackerPool[i];

            if (tracker.target && !tracker.target.death) {
                this.UpdateTrackerScreenPos(tracker);
            }
            else {
                this.trackerPool.splice(i, 1);
                i--;

                if (tracker.node) {
                    PoolManager.putNode(Tools.getEnumName(GameStickerType, tracker.type), tracker.node);
                    //     // tracker.node.destroy();
                }
            }
        }

        this._time += deltaTime;
        if (this._time >= this._radarCoolTime) {
            this._time = 0;
            if (this._enableRadar && !this._startRadar && Global.gameManager.playerUnit) {
                this._startRadar = true;
                this.schedule(this.StartRadar, this._radarTick);
            }
        }
    }

    StartRadar() {

        // 排序 Tracker，根据在屏幕上的角度逆时针排列
        this.trackerPool.sort((a, b) => {
            const angleA = this.getTrackerAngle(a);
            const angleB = this.getTrackerAngle(b);
            return angleA - angleB; // 按照角度排序
        });

        this.scanRadar();
    }

    /**雷达扫描起始角度 */
    private _startRadarAngle: number = 90;
    /**雷达累计扫描的角度 */
    private _currentRadarAngleSum: number = 0;
    // 扫描雷达的逻辑
    private scanRadar() {
        const startAngle = (this._currentRadarAngleSum + this._startRadarAngle + 360) % 360; // 当前扫描的起始角度
        const endAngle = startAngle + this._radarTickAngle; // 扫描的结束角度

        // 找出在当前扫描范围内的 Tracker
        const trackedInRange: Tracker[] = [];
        for (const tracker of this.trackerPool) {
            const angle = this.getTrackerAngle(tracker);
            // 将角度范围归一化到 0-360
            const normalizedAngle = (angle + 360) % 360;
            if (normalizedAngle >= startAngle && normalizedAngle < endAngle) {
                trackedInRange.push(tracker);
            }
        }

        trackedInRange.forEach((tracker) => {
            tracker.UpdateLabel();
        })

        // 使用三角函数计算坐标
        // this.radarRenderer(endAngle);

        // 更新当前雷达角度
        this._currentRadarAngleSum += this._radarTickAngle;
        if (this._currentRadarAngleSum >= 360) {
            this._currentRadarAngleSum = 0;
            this.unschedule(this.StartRadar);
            this._startRadar = false;
            this.graphics.clear();
        }
    }

    private _temp_pos: Vec3 = new Vec3;
    /**
     * 渲染雷达线
     * @param angle 角度
     */
    private radarRenderer(angle) {
        const radians = angle * (Math.PI / 180);

        this.graphics.clear();
        this.graphics.strokeColor = Color.WHITE;
        this.graphics.lineWidth = 2; // 线宽
        let x, y = 0;

        let player = Global.gameManager.playerUnit;
        if (player && !player.death) {
            this.tran.convertToNodeSpaceAR(player.unitWorldPos, this._temp_pos);
            x = this._temp_pos.x;
            y = this._temp_pos.y;
        }
        this.graphics.moveTo(x, y);

        x = 1000 * Math.cos(radians);
        y = 1000 * Math.sin(radians);
        this.graphics.lineTo(x, y);
        this.graphics.stroke();

        // this.graphics.clear();
        // this.graphics.strokeColor = Color.WHITE;
        // this.graphics.lineWidth = 2; // 线宽
        // this._temp_pos.set(0, 0, 0);

        // x = 1000 * Math.cos(radians);
        // y = 1000 * Math.sin(radians);
        // this._temp_pos.set(x, y, 0);
        // this.tran.convertToWorldSpaceAR(this._temp_pos, this._temp_pos);
        // this.RestrictedToEdgeOfScreenPos(this._temp_pos, this._temp_pos);
        // this.tran.convertToNodeSpaceAR(this._temp_pos, this._temp_pos);
        // this.graphics.moveTo(this._temp_pos.x, this._temp_pos.y);
        // let _p = this._temp_pos.clone();
        // _p.normalize().set(-_p.x, -_p.y).multiplyScalar(100);
        // this._temp_pos.add(_p);

        // this.graphics.lineTo(this._temp_pos.x, this._temp_pos.y);
        // this.graphics.stroke();
    }

    // 获取 Tracker 在屏幕上的角度
    private getTrackerAngle(tracker: Tracker): number {
        const trackerPos = tracker.node.worldPosition;
        const angle = Math.atan2(trackerPos.y - this.screenCenter.y, trackerPos.x - this.screenCenter.x);
        return angle * (180 / Math.PI); // 转换为角度
    }

    AddSticker_toTarget(target: Unit, type: GameStickerType, msg?: string): Node {
        let stickerMap = this.allStickerMap.get(type) || new Map<Unit, GameSticker[]>();
        this.allStickerMap.set(type, stickerMap);
        let stickerArr = stickerMap.get(target) || [];
        stickerMap.set(target, stickerArr);

        let trackerPre: Prefab = AssetsMgr.prefabMap.get(Tools.getEnumName(GameStickerType, type));
        if (!trackerPre) {
            return null;
        }

        target.on(this, UnitEvent.OnDestroy, () => {
            this.RemoveSticker_toTarget(type, target);
        });

        let inst: Node = null;

        //对于敌对经济标签 如果目标存在使用已存在的对象
        if (type == GameStickerType.PlanetEconomicSticker) {
            let existingSticker = this.allStickerMap.get(type)?.get(target)?.[0];
            if (existingSticker && existingSticker.isValid) {
                inst = existingSticker.node;
                inst.active = true;
            }
        }

        if (!inst) {
            inst = PoolManager.getNode(trackerPre);
        }

        if (!inst || !inst.isValid) {
            return;
        }

        inst.setParent(this.node);
        let sticker = inst.getComponent(GameSticker);
        sticker.setTarget(target);

        if (type == GameStickerType.Tracker) {
            this.scheduleOnce(() => {
                this.trackerPool.push(sticker as Tracker);
            }, 1);
        }

        if (!stickerArr.includes(sticker)) {
            stickerArr.push(sticker);
        }

        return inst;
    }

    RemoveSticker_toTarget(type: GameStickerType, target?: Unit) {
        let stickerMap = this.allStickerMap.get(type) || new Map<Unit, GameSticker[]>();
        this.allStickerMap.set(type, stickerMap);

        if (!target) {
            stickerMap.forEach((v, k) => {
                for (let i = v.length - 1; i >= 0; i--) { // 从后向前遍历
                    if (type == v[i].type) {
                        if (v[i].isValid && v[i].node.active) {
                            PoolManager.putNode(Tools.getEnumName(GameStickerType, type), v[i].node);
                        }
                        v.splice(i, 1); // 安全删除
                    }
                }
            })
        }
        else {

            let stickerArr = stickerMap.get(target) || [];
            stickerMap.set(target, stickerArr);
            if (stickerArr.length > 0) {
                for (let i = stickerArr.length - 1; i >= 0; i--) { // 从后向前遍历
                    if (stickerArr[i].isValid && stickerArr[i].node.active) {
                        PoolManager.putNode(Tools.getEnumName(GameStickerType, type), stickerArr[i].node);
                    }
                    stickerArr.splice(i, 1); // 安全删除
                }
            }
        }
    }

    //找到出地图上的其他星球相对于玩家的雷达位置
    UpdateTrackerScreenPos(tracker: Tracker) {

        this.node.getWorldPosition(tracker.toward);
        let is_out = this.RestrictedToEdgeOfScreenPos(tracker.target.unitWorldPos, tracker.node);
        if (!Global.TrackerDebug) {
            tracker.selfOpacity.opacity = is_out ? 255 : 0;
        }
        else {
            tracker.selfOpacity.opacity = 255;
            if (!is_out) {
                let pos = tracker.target.unitWorldPos;
                pos.x += 50;
                pos.y -= 50;
                tracker.node.setWorldPosition(pos);
            }
        }
    }

    /**限制在屏幕边缘 */
    RestrictedToEdgeOfScreenPos(world_pos: Vec3, out?: Vec3 | Node): boolean {
        let radarPos = world_pos;

        let screenSize = Global.designScreenSize;//随摄像机视角影响
        screenSize.width *= Global.CameraOrthoScale;
        screenSize.height *= Global.CameraOrthoScale;

        let space = this.space * Global.CameraOrthoScale;

        //如果项目勾选了适配高度就不用手动修改适配了
        //如果项目都勾选了，，就是另一种情况，此时获取到的窗口大小并不是相机所看到的屏幕大小
        let left = this.screenCenter.x - screenSize.width * Global.screenAdjustScale.x / 2 + space;
        let right = this.screenCenter.x + screenSize.width * Global.screenAdjustScale.x / 2 - space;
        let top = this.screenCenter.y + screenSize.height / 2 - space;//* Global.screenAdjustScale.y / 2;
        let bottom = this.screenCenter.y - screenSize.height / 2 + space;// * Global.screenAdjustScale.y / 2;
        let otherPos = world_pos;

        let is_out = false;
        if (otherPos.x > right) {
            radarPos.x = right;
            is_out = true;
        }
        else if (otherPos.x < left) {
            radarPos.x = left;
            is_out = true;
        }

        if (otherPos.y > top) {
            radarPos.y = top;
            is_out = true;
        }
        else if (otherPos.y < bottom) {
            radarPos.y = bottom;
            is_out = true;
        }

        if (out) {
            if (out instanceof Vec3) {
                out.set(radarPos.x, radarPos.y, radarPos.z);
            }
            else if (out instanceof Node) {
                out.setWorldPosition(radarPos);
            }
        }

        return is_out;
    }
}


